﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Common;
using EshubaAnalyser;

namespace EshubaDownloader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void MainWindow_OnLoaded(object sender, RoutedEventArgs e)
        {
            this.Dispatcher.BeginInvoke(new Action(LoadCache));
            Action action = () =>
                                {
                                    OnBuzy("正在从" + Analyser.WebSite + "获取数据。");
                                    Analyser.DoAnalyse();
                                    this.Dispatcher.BeginInvoke(new Action(LoadCache));
                                };
            action.BeginInvoke(
                delegate
                {
                    NotBuzy("获得了一级菜单数据。");
                }, null);
        }

        private void BuildTree(EshubaMenu parentNode)
        {
            if (EshubaCache.Instance.MenuCache == null) return;
            parentNode.Children.Clear();
            lock (EshubaCache.Instance)
            {
                foreach (EshubaMenu menu in EshubaCache.Instance.MenuCache.Values.Where(m => m.ParentGuid.Equals(parentNode.Guid)))
                {
                    parentNode.Children.Add(menu);
                    if (EshubaCache.Instance.MenuCache.Values.Any(m => m.ParentGuid.Equals(menu.Guid)))
                    {
                        BuildTree(menu);
                    }
                } 
            }
        }

        private void OnBuzy(string text)
        {
            this.Dispatcher.BeginInvoke(
                   new Action(
                       () =>
                       {
                           this.imgLoading.Visibility = Visibility.Visible;
                           this.lblInfo.Content = text;
                       }));
        }

        private void NotBuzy(string text)
        {
            this.Dispatcher.BeginInvoke(
                new Action(
                    () =>
                    {
                        this.imgLoading.Visibility = Visibility.Collapsed;
                        this.lblInfo.Content = text;
                    }));
            Action clearAction =
                () =>
                {
                    Thread.Sleep(5 * 1000);
                    this.Dispatcher.BeginInvoke(
                        new Action(
                            () =>
                            {
                                if (this.lblInfo.Content.Equals("就绪"))
                                    this.lblInfo.Content = "就绪";
                            }));
                };
            clearAction.BeginInvoke(null, null);
        }

        private void LoadCache()
        {
            if (EshubaCache.Instance.MenuCache == null) return;
            BuildTree(EshubaCache.Instance.MenuTreeCache);
            this.tvMenu.ItemsSource = EshubaCache.Instance.MenuTreeCache.Children;
        }

        private void TvMenu_OnSelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
        {
            if (sender == null || e == null) return;
            if (!(e.NewValue is EshubaMenu)) return;
            EshubaMenu menu = e.NewValue as EshubaMenu;
            this.Dispatcher.BeginInvoke(
                new Action(
                    () =>
                    {
                        List<EshubaBook> bookList = EshubaCache.Instance.BookCache.Values.Where(b => b.ParentGuid == menu.Guid).ToList();
                        this.lbBooks.ItemsSource = bookList;
                    }));
            Action action = () =>
            {
                OnBuzy("正在从" + Analyser.WebSite + "获取【" + menu.Text + "】下的新数据。");
                LoadChild(menu);
            };
            action.BeginInvoke(
                delegate
                {
                    NotBuzy("分类【" + menu.Text + "】下数据或许完毕。");
                }, null);
        }

        private void LoadChild(EshubaMenu parentNode)
        {
            var childs = Analyser.GetChildMenu(parentNode);
            List<EshubaBook> books = new List<EshubaBook>();
            lock (EshubaCache.Instance)
            {
                if (!EshubaCache.Instance.MenuCache.Values.Any(m => m.ParentGuid == parentNode.Guid))
                    books = Analyser.GetClassifyBookList(parentNode); 
            }
            this.Dispatcher.BeginInvoke(
                new Action(
                    () =>
                    {
                        foreach (var child in childs)
                        {
                            foreach (EshubaMenu tvNode in parentNode.Children)
                            {
                                string url = tvNode.Url;
                                if (url == child.Url) goto BreakLoop;
                            }
                            parentNode.Children.Add(child);
                        BreakLoop:
                            continue;
                        }
                        if (parentNode.Children.Count <= 0)
                        {
                            this.lbBooks.ItemsSource = books;
                        }
                    }));
        }

        private void LbBooks_OnSelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender == null || e == null) return;
            if (!(e.AddedItems[0] is EshubaBook)) return;
            EshubaBook book = e.AddedItems[0] as EshubaBook;
            //this.tbName.Text = "名称：" + book.Name;
            //this.tbUrl.Text = "地址：" + book.Url;
        }

        private void DownloadClick(object sender, RoutedEventArgs e)
        {
            if (sender == null || e == null) return;
            if (!(sender is Button)) return;
            Guid guid = (Guid)(sender as Button).Tag;
            EshubaBook book = EshubaCache.Instance.BookCache.TryGetValue(guid);
            if (book == null) return;
            string downloadUrl = Analyser.GetDownloadUrl(book);
            Downloader.Download(book);
        }
    }
}
